3 * Copyright © 2006, 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\MediaWikiServices
;
23 use Wikimedia\Rdbms\IResultWrapper
;
24 use Wikimedia\Rdbms\IDatabase
;
27 * This class contains a list of pages that the client has requested.
28 * Initially, when the client passes in titles=, pageids=, or revisions=
29 * parameter, an instance of the ApiPageSet class will normalize titles,
30 * determine if the pages/revisions exist, and prefetch any additional page
33 * When a generator is used, the result of the generator will become the input
34 * for the second instance of this class, and all subsequent actions will use
35 * the second instance for all their work.
38 * @since 1.21 derives from ApiBase instead of ApiQueryBase
40 class ApiPageSet
extends ApiBase
{
42 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
45 const DISABLE_GENERATORS
= 1;
49 private $mResolveRedirects;
50 private $mConvertTitles;
51 private $mAllowGenerator;
53 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
54 private $mTitles = [];
55 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
56 private $mGoodPages = []; // [ns][dbkey] => page_id
57 private $mGoodTitles = [];
58 private $mMissingPages = []; // [ns][dbkey] => fake page_id
59 private $mMissingTitles = [];
60 /** @var array [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
61 private $mInvalidTitles = [];
62 private $mMissingPageIDs = [];
63 private $mRedirectTitles = [];
64 private $mSpecialTitles = [];
65 private $mAllSpecials = []; // separate from mAllPages to avoid breaking getAllTitlesByNamespace()
66 private $mNormalizedTitles = [];
67 private $mInterwikiTitles = [];
69 private $mPendingRedirectIDs = [];
70 private $mPendingRedirectSpecialPages = []; // [dbkey] => [ Title $from, Title $to ]
71 private $mResolvedRedirectTitles = [];
72 private $mConvertedTitles = [];
73 private $mGoodRevIDs = [];
74 private $mLiveRevIDs = [];
75 private $mDeletedRevIDs = [];
76 private $mMissingRevIDs = [];
77 private $mGeneratorData = []; // [ns][dbkey] => data array
78 private $mFakePageId = -1;
79 private $mCacheMode = 'public';
80 private $mRequestedPageFields = [];
82 private $mDefaultNamespace = NS_MAIN
;
83 /** @var callable|null */
84 private $mRedirectMergePolicy;
87 * Add all items from $values into the result
88 * @param array $result Output
89 * @param array $values Values to add
90 * @param string[] $flags The names of boolean flags to mark this element
91 * @param string $name If given, name of the value
93 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
94 foreach ( $values as $val ) {
95 if ( $val instanceof Title
) {
97 ApiQueryBase
::addTitleInfo( $v, $val );
98 } elseif ( $name !== null ) {
99 $v = [ $name => $val ];
103 foreach ( $flags as $flag ) {
111 * @param ApiBase $dbSource Module implementing getDB().
112 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
113 * @param int $flags Zero or more flags like DISABLE_GENERATORS
114 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
115 * @since 1.21 accepts $flags instead of two boolean values
117 public function __construct( ApiBase
$dbSource, $flags = 0, $defaultNamespace = NS_MAIN
) {
118 parent
::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
119 $this->mDbSource
= $dbSource;
120 $this->mAllowGenerator
= ( $flags & self
::DISABLE_GENERATORS
) == 0;
121 $this->mDefaultNamespace
= $defaultNamespace;
123 $this->mParams
= $this->extractRequestParams();
124 $this->mResolveRedirects
= $this->mParams
['redirects'];
125 $this->mConvertTitles
= $this->mParams
['converttitles'];
129 * In case execute() is not called, call this method to mark all relevant parameters as used
130 * This prevents unused parameters from being reported as warnings
132 public function executeDryRun() {
133 $this->executeInternal( true );
137 * Populate the PageSet from the request parameters.
139 public function execute() {
140 $this->executeInternal( false );
144 * Populate the PageSet from the request parameters.
145 * @param bool $isDryRun If true, instantiates generator, but only to mark
146 * relevant parameters as used
148 private function executeInternal( $isDryRun ) {
149 $generatorName = $this->mAllowGenerator ?
$this->mParams
['generator'] : null;
150 if ( isset( $generatorName ) ) {
151 $dbSource = $this->mDbSource
;
152 if ( !$dbSource instanceof ApiQuery
) {
153 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
154 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
156 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
157 if ( $generator === null ) {
158 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
160 if ( !$generator instanceof ApiQueryGeneratorBase
) {
161 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
163 // Create a temporary pageset to store generator's output,
164 // add any additional fields generator may need, and execute pageset to populate titles/pageids
165 $tmpPageSet = new ApiPageSet( $dbSource, self
::DISABLE_GENERATORS
);
166 $generator->setGeneratorMode( $tmpPageSet );
167 $this->mCacheMode
= $generator->getCacheMode( $generator->extractRequestParams() );
170 $generator->requestExtraData( $tmpPageSet );
172 $tmpPageSet->executeInternal( $isDryRun );
174 // populate this pageset with the generator output
176 $generator->executeGenerator( $this );
178 // Avoid PHP 7.1 warning of passing $this by reference
180 Hooks
::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
182 // Prevent warnings from being reported on these parameters
183 $main = $this->getMain();
184 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
185 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
190 $this->resolvePendingRedirects();
193 // Only one of the titles/pageids/revids is allowed at the same time
195 if ( isset( $this->mParams
['titles'] ) ) {
196 $dataSource = 'titles';
198 if ( isset( $this->mParams
['pageids'] ) ) {
199 if ( isset( $dataSource ) ) {
202 'apierror-invalidparammix-cannotusewith',
203 $this->encodeParamName( 'pageids' ),
204 $this->encodeParamName( $dataSource )
209 $dataSource = 'pageids';
211 if ( isset( $this->mParams
['revids'] ) ) {
212 if ( isset( $dataSource ) ) {
215 'apierror-invalidparammix-cannotusewith',
216 $this->encodeParamName( 'revids' ),
217 $this->encodeParamName( $dataSource )
222 $dataSource = 'revids';
226 // Populate page information with the original user input
227 switch ( $dataSource ) {
229 $this->initFromTitles( $this->mParams
['titles'] );
232 $this->initFromPageIds( $this->mParams
['pageids'] );
235 if ( $this->mResolveRedirects
) {
236 $this->addWarning( 'apiwarn-redirectsandrevids' );
238 $this->mResolveRedirects
= false;
239 $this->initFromRevIDs( $this->mParams
['revids'] );
242 // Do nothing - some queries do not need any of the data sources.
250 * Check whether this PageSet is resolving redirects
253 public function isResolvingRedirects() {
254 return $this->mResolveRedirects
;
258 * Return the parameter name that is the source of data for this PageSet
260 * If multiple source parameters are specified (e.g. titles and pageids),
261 * one will be named arbitrarily.
263 * @return string|null
265 public function getDataSource() {
266 if ( $this->mAllowGenerator
&& isset( $this->mParams
['generator'] ) ) {
269 if ( isset( $this->mParams
['titles'] ) ) {
272 if ( isset( $this->mParams
['pageids'] ) ) {
275 if ( isset( $this->mParams
['revids'] ) ) {
283 * Request an additional field from the page table.
284 * Must be called before execute()
285 * @param string $fieldName Field name
287 public function requestField( $fieldName ) {
288 $this->mRequestedPageFields
[$fieldName] = null;
292 * Get the value of a custom field previously requested through
294 * @param string $fieldName Field name
295 * @return mixed Field value
297 public function getCustomField( $fieldName ) {
298 return $this->mRequestedPageFields
[$fieldName];
302 * Get the fields that have to be queried from the page table:
303 * the ones requested through requestField() and a few basic ones
305 * @return array Array of field names
307 public function getPageTableFields() {
308 // Ensure we get minimum required fields
309 // DON'T change this order
311 'page_namespace' => null,
312 'page_title' => null,
316 if ( $this->mResolveRedirects
) {
317 $pageFlds['page_is_redirect'] = null;
320 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
321 $pageFlds['page_content_model'] = null;
324 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
325 $pageFlds['page_lang'] = null;
328 foreach ( LinkCache
::getSelectFields() as $field ) {
329 $pageFlds[$field] = null;
332 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields
);
334 return array_keys( $pageFlds );
338 * Returns an array [ns][dbkey] => page_id for all requested titles.
339 * page_id is a unique negative number in case title was not found.
340 * Invalid titles will also have negative page IDs and will be in namespace 0
343 public function getAllTitlesByNamespace() {
344 return $this->mAllPages
;
348 * All Title objects provided.
351 public function getTitles() {
352 return $this->mTitles
;
356 * Returns the number of unique pages (not revisions) in the set.
359 public function getTitleCount() {
360 return count( $this->mTitles
);
364 * Returns an array [ns][dbkey] => page_id for all good titles.
367 public function getGoodTitlesByNamespace() {
368 return $this->mGoodPages
;
372 * Title objects that were found in the database.
373 * @return Title[] Array page_id (int) => Title (obj)
375 public function getGoodTitles() {
376 return $this->mGoodTitles
;
380 * Returns the number of found unique pages (not revisions) in the set.
383 public function getGoodTitleCount() {
384 return count( $this->mGoodTitles
);
388 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
389 * fake_page_id is a unique negative number.
392 public function getMissingTitlesByNamespace() {
393 return $this->mMissingPages
;
397 * Title objects that were NOT found in the database.
398 * The array's index will be negative for each item
401 public function getMissingTitles() {
402 return $this->mMissingTitles
;
406 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
409 public function getGoodAndMissingTitlesByNamespace() {
410 return $this->mGoodAndMissingPages
;
414 * Title objects for good and missing titles.
417 public function getGoodAndMissingTitles() {
418 return $this->mGoodTitles +
$this->mMissingTitles
;
422 * Titles that were deemed invalid by Title::newFromText()
423 * The array's index will be unique and negative for each item
424 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
426 public function getInvalidTitlesAndReasons() {
427 return $this->mInvalidTitles
;
431 * Page IDs that were not found in the database
432 * @return array Array of page IDs
434 public function getMissingPageIDs() {
435 return $this->mMissingPageIDs
;
439 * Get a list of redirect resolutions - maps a title to its redirect
440 * target, as an array of output-ready arrays
443 public function getRedirectTitles() {
444 return $this->mRedirectTitles
;
448 * Get a list of redirect resolutions - maps a title to its redirect
449 * target. Includes generator data for redirect source when available.
450 * @param ApiResult|null $result
451 * @return array Array of prefixed_title (string) => Title object
454 public function getRedirectTitlesAsResult( $result = null ) {
456 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
458 'from' => strval( $titleStrFrom ),
459 'to' => $titleTo->getPrefixedText(),
461 if ( $titleTo->hasFragment() ) {
462 $r['tofragment'] = $titleTo->getFragment();
464 if ( $titleTo->isExternal() ) {
465 $r['tointerwiki'] = $titleTo->getInterwiki();
467 if ( isset( $this->mResolvedRedirectTitles
[$titleStrFrom] ) ) {
468 $titleFrom = $this->mResolvedRedirectTitles
[$titleStrFrom];
469 $ns = $titleFrom->getNamespace();
470 $dbkey = $titleFrom->getDBkey();
471 if ( isset( $this->mGeneratorData
[$ns][$dbkey] ) ) {
472 $r = array_merge( $this->mGeneratorData
[$ns][$dbkey], $r );
478 if ( !empty( $values ) && $result ) {
479 ApiResult
::setIndexedTagName( $values, 'r' );
486 * Get a list of title normalizations - maps a title to its normalized
488 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
490 public function getNormalizedTitles() {
491 return $this->mNormalizedTitles
;
495 * Get a list of title normalizations - maps a title to its normalized
496 * version in the form of result array.
497 * @param ApiResult|null $result
498 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
501 public function getNormalizedTitlesAsResult( $result = null ) {
503 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
504 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
505 $encode = $contLang->normalize( $rawTitleStr ) !== $rawTitleStr;
507 'fromencoded' => $encode,
508 'from' => $encode ?
rawurlencode( $rawTitleStr ) : $rawTitleStr,
512 if ( !empty( $values ) && $result ) {
513 ApiResult
::setIndexedTagName( $values, 'n' );
520 * Get a list of title conversions - maps a title to its converted
522 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
524 public function getConvertedTitles() {
525 return $this->mConvertedTitles
;
529 * Get a list of title conversions - maps a title to its converted
530 * version as a result array.
531 * @param ApiResult|null $result
532 * @return array Array of (from, to) strings
535 public function getConvertedTitlesAsResult( $result = null ) {
537 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
539 'from' => $rawTitleStr,
543 if ( !empty( $values ) && $result ) {
544 ApiResult
::setIndexedTagName( $values, 'c' );
551 * Get a list of interwiki titles - maps a title to its interwiki
553 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
555 public function getInterwikiTitles() {
556 return $this->mInterwikiTitles
;
560 * Get a list of interwiki titles - maps a title to its interwiki
562 * @param ApiResult|null $result
564 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
567 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
569 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
571 'title' => $rawTitleStr,
572 'iw' => $interwikiStr,
575 $title = Title
::newFromText( $rawTitleStr );
576 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT
);
580 if ( !empty( $values ) && $result ) {
581 ApiResult
::setIndexedTagName( $values, 'i' );
588 * Get an array of invalid/special/missing titles.
590 * @param array $invalidChecks List of types of invalid titles to include.
591 * Recognized values are:
592 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
593 * - special: Titles from $this->getSpecialTitles()
594 * - missingIds: ids from $this->getMissingPageIDs()
595 * - missingRevIds: ids from $this->getMissingRevisionIDs()
596 * - missingTitles: Titles from $this->getMissingTitles()
597 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
598 * @return array Array suitable for inclusion in the response
601 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
602 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
605 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
606 self
::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
608 if ( in_array( 'special', $invalidChecks ) ) {
611 foreach ( $this->getSpecialTitles() as $title ) {
612 if ( $title->isKnown() ) {
618 self
::addValues( $result, $unknown, [ 'special', 'missing' ] );
619 self
::addValues( $result, $known, [ 'special' ] );
621 if ( in_array( 'missingIds', $invalidChecks ) ) {
622 self
::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
624 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
625 self
::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
627 if ( in_array( 'missingTitles', $invalidChecks ) ) {
630 foreach ( $this->getMissingTitles() as $title ) {
631 if ( $title->isKnown() ) {
637 self
::addValues( $result, $unknown, [ 'missing' ] );
638 self
::addValues( $result, $known, [ 'missing', 'known' ] );
640 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
641 self
::addValues( $result, $this->getInterwikiTitlesAsResult() );
648 * Get the list of valid revision IDs (requested with the revids= parameter)
649 * @return array Array of revID (int) => pageID (int)
651 public function getRevisionIDs() {
652 return $this->mGoodRevIDs
;
656 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
657 * @return array Array of revID (int) => pageID (int)
659 public function getLiveRevisionIDs() {
660 return $this->mLiveRevIDs
;
664 * Get the list of revision IDs that were associated with deleted titles.
665 * @return array Array of revID (int) => pageID (int)
667 public function getDeletedRevisionIDs() {
668 return $this->mDeletedRevIDs
;
672 * Revision IDs that were not found in the database
673 * @return array Array of revision IDs
675 public function getMissingRevisionIDs() {
676 return $this->mMissingRevIDs
;
680 * Revision IDs that were not found in the database as result array.
681 * @param ApiResult|null $result
682 * @return array Array of revision IDs
685 public function getMissingRevisionIDsAsResult( $result = null ) {
687 foreach ( $this->getMissingRevisionIDs() as $revid ) {
692 if ( !empty( $values ) && $result ) {
693 ApiResult
::setIndexedTagName( $values, 'rev' );
700 * Get the list of titles with negative namespace
703 public function getSpecialTitles() {
704 return $this->mSpecialTitles
;
708 * Returns the number of revisions (requested with revids= parameter).
709 * @return int Number of revisions.
711 public function getRevisionCount() {
712 return count( $this->getRevisionIDs() );
716 * Populate this PageSet from a list of Titles
717 * @param array $titles Array of Title objects
719 public function populateFromTitles( $titles ) {
720 $this->initFromTitles( $titles );
724 * Populate this PageSet from a list of page IDs
725 * @param array $pageIDs Array of page IDs
727 public function populateFromPageIDs( $pageIDs ) {
728 $this->initFromPageIds( $pageIDs );
732 * Populate this PageSet from a rowset returned from the database
734 * Note that the query result must include the columns returned by
735 * $this->getPageTableFields().
737 * @param IDatabase $db
738 * @param IResultWrapper $queryResult
740 public function populateFromQueryResult( $db, $queryResult ) {
741 $this->initFromQueryResult( $queryResult );
745 * Populate this PageSet from a list of revision IDs
746 * @param array $revIDs Array of revision IDs
748 public function populateFromRevisionIDs( $revIDs ) {
749 $this->initFromRevIDs( $revIDs );
753 * Extract all requested fields from the row received from the database
754 * @param stdClass $row Result row
756 public function processDbRow( $row ) {
757 // Store Title object in various data structures
758 $title = Title
::newFromRow( $row );
760 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
761 $linkCache->addGoodLinkObjFromRow( $title, $row );
763 $pageId = (int)$row->page_id
;
764 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
765 $this->mTitles
[] = $title;
767 if ( $this->mResolveRedirects
&& $row->page_is_redirect
== '1' ) {
768 $this->mPendingRedirectIDs
[$pageId] = $title;
770 $this->mGoodPages
[$row->page_namespace
][$row->page_title
] = $pageId;
771 $this->mGoodAndMissingPages
[$row->page_namespace
][$row->page_title
] = $pageId;
772 $this->mGoodTitles
[$pageId] = $title;
775 foreach ( $this->mRequestedPageFields
as $fieldName => &$fieldValues ) {
776 $fieldValues[$pageId] = $row->$fieldName;
781 * This method populates internal variables with page information
782 * based on the given array of title strings.
785 * #1 For each title, get data from `page` table
786 * #2 If page was not found in the DB, store it as missing
788 * Additionally, when resolving redirects:
789 * #3 If no more redirects left, stop.
790 * #4 For each redirect, get its target from the `redirect` table.
791 * #5 Substitute the original LinkBatch object with the new list
792 * #6 Repeat from step #1
794 * @param array $titles Array of Title objects or strings
796 private function initFromTitles( $titles ) {
797 // Get validated and normalized title objects
798 $linkBatch = $this->processTitlesArray( $titles );
799 if ( $linkBatch->isEmpty() ) {
800 // There might be special-page redirects
801 $this->resolvePendingRedirects();
805 $db = $this->getDB();
806 $set = $linkBatch->constructSet( 'page', $db );
808 // Get pageIDs data from the `page` table
809 $res = $db->select( 'page', $this->getPageTableFields(), $set,
812 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
813 $this->initFromQueryResult( $res, $linkBatch->data
, true ); // process Titles
815 // Resolve any found redirects
816 $this->resolvePendingRedirects();
820 * Does the same as initFromTitles(), but is based on page IDs instead
821 * @param array $pageids Array of page IDs
822 * @param bool $filterIds Whether the IDs need filtering
824 private function initFromPageIds( $pageids, $filterIds = true ) {
829 $pageids = array_map( 'intval', $pageids ); // paranoia
830 $remaining = array_flip( $pageids );
833 $pageids = $this->filterIDs( [ [ 'page', 'page_id' ] ], $pageids );
837 if ( !empty( $pageids ) ) {
839 'page_id' => $pageids
841 $db = $this->getDB();
843 // Get pageIDs data from the `page` table
844 $res = $db->select( 'page', $this->getPageTableFields(), $set,
848 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
850 // Resolve any found redirects
851 $this->resolvePendingRedirects();
855 * Iterate through the result of the query on 'page' table,
856 * and for each row create and store title object and save any extra fields requested.
857 * @param IResultWrapper $res DB Query result
858 * @param array $remaining Array of either pageID or ns/title elements (optional).
859 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
860 * @param bool $processTitles Must be provided together with $remaining.
861 * If true, treat $remaining as an array of [ns][title]
862 * If false, treat it as an array of [pageIDs]
864 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
865 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
866 ApiBase
::dieDebug( __METHOD__
, 'Missing $processTitles parameter when $remaining is provided' );
869 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
873 foreach ( $res as $row ) {
874 $pageId = (int)$row->page_id
;
876 // Remove found page from the list of remaining items
877 if ( isset( $remaining ) ) {
878 if ( $processTitles ) {
879 unset( $remaining[$row->page_namespace
][$row->page_title
] );
881 unset( $remaining[$pageId] );
885 // Store any extra fields requested by modules
886 $this->processDbRow( $row );
888 // Need gender information
889 if ( $nsInfo->hasGenderDistinction( $row->page_namespace
) ) {
890 $usernames[] = $row->page_title
;
895 if ( isset( $remaining ) ) {
896 // Any items left in the $remaining list are added as missing
897 if ( $processTitles ) {
898 // The remaining titles in $remaining are non-existent pages
899 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
900 foreach ( $remaining as $ns => $dbkeys ) {
901 foreach ( array_keys( $dbkeys ) as $dbkey ) {
902 $title = Title
::makeTitle( $ns, $dbkey );
903 $linkCache->addBadLinkObj( $title );
904 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
905 $this->mMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
906 $this->mGoodAndMissingPages
[$ns][$dbkey] = $this->mFakePageId
;
907 $this->mMissingTitles
[$this->mFakePageId
] = $title;
908 $this->mFakePageId
--;
909 $this->mTitles
[] = $title;
911 // need gender information
912 if ( $nsInfo->hasGenderDistinction( $ns ) ) {
913 $usernames[] = $dbkey;
918 // The remaining pageids do not exist
919 if ( !$this->mMissingPageIDs
) {
920 $this->mMissingPageIDs
= array_keys( $remaining );
922 $this->mMissingPageIDs
= array_merge( $this->mMissingPageIDs
, array_keys( $remaining ) );
927 // Get gender information
928 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
929 $genderCache->doQuery( $usernames, __METHOD__
);
933 * Does the same as initFromTitles(), but is based on revision IDs
935 * @param array $revids Array of revision IDs
937 private function initFromRevIDs( $revids ) {
942 $revids = array_map( 'intval', $revids ); // paranoia
943 $db = $this->getDB();
945 $remaining = array_flip( $revids );
947 $revids = $this->filterIDs( [ [ 'revision', 'rev_id' ], [ 'archive', 'ar_rev_id' ] ], $revids );
948 $goodRemaining = array_flip( $revids );
951 $tables = [ 'revision', 'page' ];
952 $fields = [ 'rev_id', 'rev_page' ];
953 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
955 // Get pageIDs data from the `page` table
956 $res = $db->select( $tables, $fields, $where, __METHOD__
);
957 foreach ( $res as $row ) {
958 $revid = (int)$row->rev_id
;
959 $pageid = (int)$row->rev_page
;
960 $this->mGoodRevIDs
[$revid] = $pageid;
961 $this->mLiveRevIDs
[$revid] = $pageid;
962 $pageids[$pageid] = '';
963 unset( $remaining[$revid] );
964 unset( $goodRemaining[$revid] );
968 // Populate all the page information
969 $this->initFromPageIds( array_keys( $pageids ), false );
971 // If the user can see deleted revisions, pull out the corresponding
972 // titles from the archive table and include them too. We ignore
973 // ar_page_id because deleted revisions are tied by title, not page_id.
974 if ( $goodRemaining && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
975 $tables = [ 'archive' ];
976 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
977 $where = [ 'ar_rev_id' => array_keys( $goodRemaining ) ];
979 $res = $db->select( $tables, $fields, $where, __METHOD__
);
981 foreach ( $res as $row ) {
982 $revid = (int)$row->ar_rev_id
;
983 $titles[$revid] = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
984 unset( $remaining[$revid] );
987 $this->initFromTitles( $titles );
989 foreach ( $titles as $revid => $title ) {
990 $ns = $title->getNamespace();
991 $dbkey = $title->getDBkey();
993 // Handle converted titles
994 if ( !isset( $this->mAllPages
[$ns][$dbkey] ) &&
995 isset( $this->mConvertedTitles
[$title->getPrefixedText()] )
997 $title = Title
::newFromText( $this->mConvertedTitles
[$title->getPrefixedText()] );
998 $ns = $title->getNamespace();
999 $dbkey = $title->getDBkey();
1002 if ( isset( $this->mAllPages
[$ns][$dbkey] ) ) {
1003 $this->mGoodRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1004 $this->mDeletedRevIDs
[$revid] = $this->mAllPages
[$ns][$dbkey];
1006 $remaining[$revid] = true;
1011 $this->mMissingRevIDs
= array_keys( $remaining );
1015 * Resolve any redirects in the result if redirect resolution was
1016 * requested. This function is called repeatedly until all redirects
1017 * have been resolved.
1019 private function resolvePendingRedirects() {
1020 if ( $this->mResolveRedirects
) {
1021 $db = $this->getDB();
1022 $pageFlds = $this->getPageTableFields();
1024 // Repeat until all redirects have been resolved
1025 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1026 while ( $this->mPendingRedirectIDs ||
$this->mPendingRedirectSpecialPages
) {
1027 // Resolve redirects by querying the pagelinks table, and repeat the process
1028 // Create a new linkBatch object for the next pass
1029 $linkBatch = $this->getRedirectTargets();
1031 if ( $linkBatch->isEmpty() ) {
1035 $set = $linkBatch->constructSet( 'page', $db );
1036 if ( $set === false ) {
1040 // Get pageIDs data from the `page` table
1041 $res = $db->select( 'page', $pageFlds, $set, __METHOD__
);
1043 // Hack: get the ns:titles stored in [ns => array(titles)] format
1044 $this->initFromQueryResult( $res, $linkBatch->data
, true );
1050 * Get the targets of the pending redirects from the database
1052 * Also creates entries in the redirect table for redirects that don't
1056 private function getRedirectTargets() {
1057 $titlesToResolve = [];
1058 $db = $this->getDB();
1060 if ( $this->mPendingRedirectIDs
) {
1069 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs
) ],
1072 foreach ( $res as $row ) {
1073 $rdfrom = (int)$row->rd_from
;
1074 $from = $this->mPendingRedirectIDs
[$rdfrom]->getPrefixedText();
1075 $to = Title
::makeTitle(
1081 $this->mResolvedRedirectTitles
[$from] = $this->mPendingRedirectIDs
[$rdfrom];
1082 unset( $this->mPendingRedirectIDs
[$rdfrom] );
1083 if ( $to->isExternal() ) {
1084 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1085 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1086 $titlesToResolve[] = $to;
1088 $this->mRedirectTitles
[$from] = $to;
1091 if ( $this->mPendingRedirectIDs
) {
1092 // We found pages that aren't in the redirect table
1094 foreach ( $this->mPendingRedirectIDs
as $id => $title ) {
1095 $page = WikiPage
::factory( $title );
1096 $rt = $page->insertRedirect();
1098 // What the hell. Let's just ignore this
1101 if ( $rt->isExternal() ) {
1102 $this->mInterwikiTitles
[$rt->getPrefixedText()] = $rt->getInterwiki();
1103 } elseif ( !isset( $this->mAllPages
[$rt->getNamespace()][$rt->getDBkey()] ) ) {
1104 $titlesToResolve[] = $rt;
1106 $from = $title->getPrefixedText();
1107 $this->mResolvedRedirectTitles
[$from] = $title;
1108 $this->mRedirectTitles
[$from] = $rt;
1109 unset( $this->mPendingRedirectIDs
[$id] );
1114 if ( $this->mPendingRedirectSpecialPages
) {
1115 foreach ( $this->mPendingRedirectSpecialPages
as $key => list( $from, $to ) ) {
1116 $fromKey = $from->getPrefixedText();
1117 $this->mResolvedRedirectTitles
[$fromKey] = $from;
1118 $this->mRedirectTitles
[$fromKey] = $to;
1119 if ( $to->isExternal() ) {
1120 $this->mInterwikiTitles
[$to->getPrefixedText()] = $to->getInterwiki();
1121 } elseif ( !isset( $this->mAllPages
[$to->getNamespace()][$to->getDBkey()] ) ) {
1122 $titlesToResolve[] = $to;
1125 $this->mPendingRedirectSpecialPages
= [];
1127 // Set private caching since we don't know what criteria the
1128 // special pages used to decide on these redirects.
1129 $this->mCacheMode
= 'private';
1132 return $this->processTitlesArray( $titlesToResolve );
1136 * Get the cache mode for the data generated by this module.
1137 * All PageSet users should take into account whether this returns a more-restrictive
1138 * cache mode than the using module itself. For possible return values and other
1139 * details about cache modes, see ApiMain::setCacheMode()
1141 * Public caching will only be allowed if *all* the modules that supply
1142 * data for a given request return a cache mode of public.
1144 * @param array|null $params
1148 public function getCacheMode( $params = null ) {
1149 return $this->mCacheMode
;
1153 * Given an array of title strings, convert them into Title objects.
1154 * Alternatively, an array of Title objects may be given.
1155 * This method validates access rights for the title,
1156 * and appends normalization values to the output.
1158 * @param array $titles Array of Title objects or strings
1161 private function processTitlesArray( $titles ) {
1163 $linkBatch = new LinkBatch();
1164 $services = MediaWikiServices
::getInstance();
1165 $contLang = $services->getContentLanguage();
1167 foreach ( $titles as $title ) {
1168 if ( is_string( $title ) ) {
1170 $titleObj = Title
::newFromTextThrow( $title, $this->mDefaultNamespace
);
1171 } catch ( MalformedTitleException
$ex ) {
1172 // Handle invalid titles gracefully
1173 if ( !isset( $this->mAllPages
[0][$title] ) ) {
1174 $this->mAllPages
[0][$title] = $this->mFakePageId
;
1175 $this->mInvalidTitles
[$this->mFakePageId
] = [
1177 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1179 $this->mFakePageId
--;
1181 continue; // There's nothing else we can do
1186 $unconvertedTitle = $titleObj->getPrefixedText();
1187 $titleWasConverted = false;
1188 if ( $titleObj->isExternal() ) {
1189 // This title is an interwiki link.
1190 $this->mInterwikiTitles
[$unconvertedTitle] = $titleObj->getInterwiki();
1192 // Variants checking
1194 $this->mConvertTitles
&& $contLang->hasVariants() && !$titleObj->exists()
1196 // Language::findVariantLink will modify titleText and titleObj into
1197 // the canonical variant if possible
1198 $titleText = is_string( $title ) ?
$title : $titleObj->getPrefixedText();
1199 $contLang->findVariantLink( $titleText, $titleObj );
1200 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1203 if ( $titleObj->getNamespace() < 0 ) {
1204 // Handle Special and Media pages
1205 $titleObj = $titleObj->fixSpecialName();
1206 $ns = $titleObj->getNamespace();
1207 $dbkey = $titleObj->getDBkey();
1208 if ( !isset( $this->mAllSpecials
[$ns][$dbkey] ) ) {
1209 $this->mAllSpecials
[$ns][$dbkey] = $this->mFakePageId
;
1211 if ( $ns === NS_SPECIAL
&& $this->mResolveRedirects
) {
1212 $spFactory = $services->getSpecialPageFactory();
1213 $special = $spFactory->getPage( $dbkey );
1214 if ( $special instanceof RedirectSpecialArticle
) {
1215 // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
1216 // RedirectSpecialPage are probably applying weird URL parameters we don't want to handle.
1217 $context = new DerivativeContext( $this );
1218 $context->setTitle( $titleObj );
1219 $context->setRequest( new FauxRequest
);
1220 $special->setContext( $context );
1221 list( /* $alias */, $subpage ) = $spFactory->resolveAlias( $dbkey );
1222 $target = $special->getRedirect( $subpage );
1226 $this->mPendingRedirectSpecialPages
[$dbkey] = [ $titleObj, $target ];
1228 $this->mSpecialTitles
[$this->mFakePageId
] = $titleObj;
1229 $this->mFakePageId
--;
1234 $linkBatch->addObj( $titleObj );
1238 // Make sure we remember the original title that was
1239 // given to us. This way the caller can correlate new
1240 // titles with the originally requested when e.g. the
1241 // namespace is localized or the capitalization is
1243 if ( $titleWasConverted ) {
1244 $this->mConvertedTitles
[$unconvertedTitle] = $titleObj->getPrefixedText();
1245 // In this case the page can't be Special.
1246 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1247 $this->mNormalizedTitles
[$title] = $unconvertedTitle;
1249 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1250 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
1253 // Need gender information
1255 MediaWikiServices
::getInstance()->getNamespaceInfo()->
1256 hasGenderDistinction( $titleObj->getNamespace() )
1258 $usernames[] = $titleObj->getText();
1261 // Get gender information
1262 $genderCache = $services->getGenderCache();
1263 $genderCache->doQuery( $usernames, __METHOD__
);
1269 * Set data for a title.
1271 * This data may be extracted into an ApiResult using
1272 * self::populateGeneratorData. This should generally be limited to
1273 * data that is likely to be particularly useful to end users rather than
1274 * just being a dump of everything returned in non-generator mode.
1276 * Redirects here will *not* be followed, even if 'redirects' was
1277 * specified, since in the case of multiple redirects we can't know which
1278 * source's data to use on the target.
1280 * @param Title $title
1281 * @param array $data
1283 public function setGeneratorData( Title
$title, array $data ) {
1284 $ns = $title->getNamespace();
1285 $dbkey = $title->getDBkey();
1286 $this->mGeneratorData
[$ns][$dbkey] = $data;
1290 * Controls how generator data about a redirect source is merged into
1291 * the generator data for the redirect target. When not set no data
1292 * is merged. Note that if multiple titles redirect to the same target
1293 * the order of operations is undefined.
1295 * Example to include generated data from redirect in target, prefering
1296 * the data generated for the destination when there is a collision:
1298 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1299 * return $current + $new;
1303 * @param callable|null $callable Recieves two array arguments, first the
1304 * generator data for the redirect target and second the generator data
1305 * for the redirect source. Returns the resulting generator data to use
1306 * for the redirect target.
1308 public function setRedirectMergePolicy( $callable ) {
1309 $this->mRedirectMergePolicy
= $callable;
1313 * Populate the generator data for all titles in the result
1315 * The page data may be inserted into an ApiResult object or into an
1316 * associative array. The $path parameter specifies the path within the
1317 * ApiResult or array to find the "pages" node.
1319 * The "pages" node itself must be an associative array mapping the page ID
1320 * or fake page ID values returned by this pageset (see
1321 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1322 * associative arrays of page data. Each of those subarrays will have the
1323 * data from self::setGeneratorData() merged in.
1325 * Data that was set by self::setGeneratorData() for pages not in the
1326 * "pages" node will be ignored.
1328 * @param ApiResult|array &$result
1329 * @param array $path
1330 * @return bool Whether the data fit
1332 public function populateGeneratorData( &$result, array $path = [] ) {
1333 if ( $result instanceof ApiResult
) {
1334 $data = $result->getResultData( $path );
1335 if ( $data === null ) {
1340 foreach ( $path as $key ) {
1341 if ( !isset( $data[$key] ) ) {
1342 // Path isn't in $result, so nothing to add, so everything
1346 $data = &$data[$key];
1349 foreach ( $this->mGeneratorData
as $ns => $dbkeys ) {
1350 if ( $ns === NS_SPECIAL
) {
1352 foreach ( $this->mSpecialTitles
as $id => $title ) {
1353 $pages[$title->getDBkey()] = $id;
1356 if ( !isset( $this->mAllPages
[$ns] ) ) {
1357 // No known titles in the whole namespace. Skip it.
1360 $pages = $this->mAllPages
[$ns];
1362 foreach ( $dbkeys as $dbkey => $genData ) {
1363 if ( !isset( $pages[$dbkey] ) ) {
1364 // Unknown title. Forget it.
1367 $pageId = $pages[$dbkey];
1368 if ( !isset( $data[$pageId] ) ) {
1369 // $pageId didn't make it into the result. Ignore it.
1373 if ( $result instanceof ApiResult
) {
1374 $path2 = array_merge( $path, [ $pageId ] );
1375 foreach ( $genData as $key => $value ) {
1376 if ( !$result->addValue( $path2, $key, $value ) ) {
1381 $data[$pageId] = array_merge( $data[$pageId], $genData );
1386 // Merge data generated about redirect titles into the redirect destination
1387 if ( $this->mRedirectMergePolicy
) {
1388 foreach ( $this->mResolvedRedirectTitles
as $titleFrom ) {
1390 while ( isset( $this->mRedirectTitles
[$dest->getPrefixedText()] ) ) {
1391 $dest = $this->mRedirectTitles
[$dest->getPrefixedText()];
1393 $fromNs = $titleFrom->getNamespace();
1394 $fromDBkey = $titleFrom->getDBkey();
1395 $toPageId = $dest->getArticleID();
1396 if ( isset( $data[$toPageId] ) &&
1397 isset( $this->mGeneratorData
[$fromNs][$fromDBkey] )
1399 // It is necessary to set both $data and add to $result, if an ApiResult,
1400 // to ensure multiple redirects to the same destination are all merged.
1401 $data[$toPageId] = call_user_func(
1402 $this->mRedirectMergePolicy
,
1404 $this->mGeneratorData
[$fromNs][$fromDBkey]
1406 if ( $result instanceof ApiResult
&&
1407 !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult
::OVERRIDE
)
1419 * Get the database connection (read-only)
1422 protected function getDB() {
1423 return $this->mDbSource
->getDB();
1426 public function getAllowedParams( $flags = 0 ) {
1429 ApiBase
::PARAM_ISMULTI
=> true,
1430 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-titles',
1433 ApiBase
::PARAM_TYPE
=> 'integer',
1434 ApiBase
::PARAM_ISMULTI
=> true,
1435 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-pageids',
1438 ApiBase
::PARAM_TYPE
=> 'integer',
1439 ApiBase
::PARAM_ISMULTI
=> true,
1440 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-revids',
1443 ApiBase
::PARAM_TYPE
=> null,
1444 ApiBase
::PARAM_HELP_MSG
=> 'api-pageset-param-generator',
1445 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'g',
1448 ApiBase
::PARAM_DFLT
=> false,
1449 ApiBase
::PARAM_HELP_MSG
=> $this->mAllowGenerator
1450 ?
'api-pageset-param-redirects-generator'
1451 : 'api-pageset-param-redirects-nogenerator',
1453 'converttitles' => [
1454 ApiBase
::PARAM_DFLT
=> false,
1455 ApiBase
::PARAM_HELP_MSG
=> [
1456 'api-pageset-param-converttitles',
1457 [ Message
::listParam( LanguageConverter
::$languagesWithVariants, 'text' ) ],
1462 if ( !$this->mAllowGenerator
) {
1463 unset( $result['generator'] );
1464 } elseif ( $flags & ApiBase
::GET_VALUES_FOR_HELP
) {
1465 $result['generator'][ApiBase
::PARAM_TYPE
] = 'submodule';
1466 $result['generator'][ApiBase
::PARAM_SUBMODULE_MAP
] = $this->getGenerators();
1472 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1473 parent
::handleParamNormalization( $paramName, $value, $rawValue );
1475 if ( $paramName === 'titles' ) {
1476 // For the 'titles' parameter, we want to split it like ApiBase would
1477 // and add any changed titles to $this->mNormalizedTitles
1478 $value = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1479 $l = count( $value );
1480 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1481 for ( $i = 0; $i < $l; $i++
) {
1482 if ( $value[$i] !== $rawValue[$i] ) {
1483 $this->mNormalizedTitles
[$rawValue[$i]] = $value[$i];
1489 private static $generators = null;
1492 * Get an array of all available generators
1495 private function getGenerators() {
1496 if ( self
::$generators === null ) {
1497 $query = $this->mDbSource
;
1498 if ( !( $query instanceof ApiQuery
) ) {
1499 // If the parent container of this pageset is not ApiQuery,
1500 // we must create it to get module manager
1501 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1504 $prefix = $query->getModulePath() . '+';
1505 $mgr = $query->getModuleManager();
1506 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1507 if ( is_subclass_of( $class, ApiQueryGeneratorBase
::class ) ) {
1508 $gens[$name] = $prefix . $name;
1512 self
::$generators = $gens;
1515 return self
::$generators;